/**
 * 
 */
package org.ztest.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringDecoder;

/**
 * @author lhl
 *
 * 2015年7月23日下午4:44:39
 */
public class HttpServerInboundHandler extends SimpleChannelInboundHandler<Object>
{
	private HttpRequest request;
	
	@Override
	public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
	{
		if (msg instanceof HttpRequest)
		{
			request = (HttpRequest) msg;
			System.out.println("URI is " + request.getUri());
			QueryStringDecoder qr = new QueryStringDecoder(request.getUri());
			System.out.println("QueryString is " + qr.parameters());
		}
		if (msg instanceof HttpContent)
		{
			HttpContent content = (HttpContent) msg;
			ByteBuf buf = content.content();
			
			buf.release();
			
			String ret = "😃👲";
			
			FullHttpResponse rsp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(ret.getBytes()));
			rsp.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
			rsp.headers().set(HttpHeaders.Names.CONTENT_LENGTH, rsp.content().readableBytes());
			if (HttpHeaders.isKeepAlive(request))
			{
				rsp.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
			}
			ctx.writeAndFlush(rsp);
		}
	}
}
